package com.cjy.demo;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class hdfs_Test1 {
    static Configuration conf= new Configuration();
    static FileSystem fs;

    public static void main(String[] args) throws Exception {
        //上传
        //up();
        //下载
        //download();
        //修改
        update();
        //查看
        //look();
        //创建
        //create();
       //Getlist();

    }

    /**
     * 查看文件
     * @throws IOException
     */
    public static void Getlist() throws IOException {
        fs=FileSystem.get(conf);
        Path path=new Path("/");
        FileStatus[] list=fs.listStatus(path);
        for (FileStatus f:list){
            System.out.println(f);
        }
    }
    /**
     * 将HDFS上文件下载到本地
     */
    public static void download() throws IOException {
        fs=FileSystem.get(conf);
        fs.copyToLocalFile(false,new Path("/t1.txt"),new Path("F:/hdfs下载的文件"),true);
        fs.close();
    }
    /**
     * 将文件上传到hdfs
     */
    public static void up() throws Exception{
        fs = FileSystem.get(conf);
        fs.copyFromLocalFile(false, new Path("F:/hdfs下载的文件/text-up.txt"), new Path("/test-up.txt"));
        fs.close();
    }
    /**
     * 修改HDFS文件名称
     * @throws IOException
     * @throws URISyntaxException
     * @throws InterruptedException
     */
    public static  void update() throws IOException, URISyntaxException, InterruptedException {
        fs=FileSystem.get(new URI("hdfs://hadoop1:9000"),conf,"hadoop1");
        Path oldName=new Path("/newTest.txt");
        Path newName=new Path("/new-test1.txt");
        fs.rename(oldName,newName);
    }

    /**
     * 创建目录和文件
     * @throws IOException
     * @throws URISyntaxException
     * @throws InterruptedException
     */
    public static void create() throws IOException, URISyntaxException, InterruptedException {
        fs=FileSystem.get(new URI("hdfs://hadoop1:9000"),conf,"hadoop1");
        Path path=new Path("/cjy");
        fs.mkdirs(path);
    }

    /**
     * 追加内容到文件
     * @throws IOException
     * @throws URISyntaxException
     * @throws InterruptedException
     */
    public static void look()throws IOException, URISyntaxException, InterruptedException {
        fs=FileSystem.get(new URI("hdfs://hadoop1:9000"),conf,"hadoop1");
        String countName="hello hdfs";
        Path path=new Path("/t1.txt");
        byte[] bytes=countName.getBytes();
        FSDataOutputStream put=fs.append(path);
        put.write(bytes);

    }
}
